package com.hsgene.order.controller.peanut;

import com.hsgene.common.ClientType;
import com.hsgene.common.dto.CommonDictDto;
import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.character.CharactersConstant;
import com.hsgene.common.util.check.ObjectAttrUtils;
import com.hsgene.common.util.date.SimpleDateUtils;
import com.hsgene.common.util.exception.CommonErrorCode;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.jwt.IJWTInfo;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.resolver.IgnoreUserToken;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.support.OrderHelper;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.mq.DcwImageModel;
import com.hsgene.order.condition.GeneticTestingOrderCondition;
import com.hsgene.order.condition.GeneticTestingOrderField;
import com.hsgene.order.condition.QueryTestingProductOrderCondition;
import com.hsgene.order.constants.v1.OrderStatus;
import com.hsgene.order.constants.v1.UploadDcwEnum;
import com.hsgene.order.domain.OrderCancelDto;
import com.hsgene.order.domain.OrderPackageDetail;
import com.hsgene.order.domain.reserve.CompleteOrderResultInfo;
import com.hsgene.order.domain.reserve.GeneticCompletePatientInfo;
import com.hsgene.order.domain.v1.GeneticTestingExpressDelivery;
import com.hsgene.order.domain.v1.GeneticTestingOrder;
import com.hsgene.order.dto.console.OrderUpdateRealPriceDto;
import com.hsgene.order.dto.console.SignDto;
import com.hsgene.order.dto.console.detail.OrderBaseInfo;
import com.hsgene.order.dto.peanut.*;
import com.hsgene.order.dto.v1.GeneticTestingExpressDeliveryDto;
import com.hsgene.order.dto.v1.OrderConfirmReceiptDto;
import com.hsgene.order.dto.v1.UploadDcwDetailsDto;
import com.hsgene.order.exception.AppletsOrderErrorCode;
import com.hsgene.order.exception.ObjectAttributeInfoEnum;
import com.hsgene.order.exception.OrderErrorCode;
import com.hsgene.order.service.AppletsOrderService;
import com.hsgene.order.service.ConsoleOrderService;
import com.hsgene.order.service.OrderService;
import com.hsgene.order.service.api.GeneratorService;
import com.hsgene.order.service.api.MessageService;
import com.hsgene.order.utils.JwtToken;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;

/**
 * 花生仁订单接口
 *
 * @author wangbing
 * @version 1.0, 2018/9/18
 */
@RestController
@RequestMapping("/v1.0/genetic/testing")
public class OrderController {

    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(OrderController.class);

    // 查询普通订单列表
    private final static String QUERY_NORMAL_ORDER = "normal";
    // 查询超期检测列表
    private final static String QUERY_POSTPONE_ORDER = "postpone";

    private static Map<String, String> sampleMap = new HashMap<>();

    @Resource
    private OrderService orderService;

    @Resource
    private JwtToken jwtToken;

    @Resource
    private AppletsOrderService appletsOrderService;

    @Resource
    private ConsoleOrderService consoleOrderService;

    @PostConstruct
    private void init() {
        //切片、白片需要数量、医院编码
        sampleMap.put("1", "whiteCount");
        //蜡块需要医院编码
        sampleMap.put("2", "hospitalCode");
        //寄回蜡块
        sampleMap.put("3", "sendWaxBlock");
        //血液需要采血管照片
        sampleMap.put("4", "bloodSampleImages");

    }

    /**
     * 花生仁地服基因检测单分页查询
     *
     * @param size              分页大小(默认值:10)
     * @param page              页码
     * @param orderNo           订单编号
     * @param groundServantName 地服姓名
     * @param patientName       患者姓名
     * @param doctorPhone       医生电话
     * @param agencyName        机构名称
     * @param sampleBarcode     样本条码
     * @param orderOrigin       订单来源
     * @param sign              标记(0-未标记,1已标记待确认,2-已确认)
     * @param listType          页码检测单前端分类【new-新订单,ongoing-进行中,end-已结束,addition-样本补寄】
     * @param status            订单状态集合
     * @param keywords          关键词(匹配订单编号，患者姓名，用户姓名)
     * @param doctorName        医生姓名
     * @param hasDcw            是否上传dcw(1是已上传，0是未上传)
     * @param startDate         按下单日期搜索开始日期
     * @param endDate           按下单日期搜索结束日期
     * @param orderBy           排序规则【0-按下单时间倒排序，1-按更新时间倒排序】
     * @param payerType         付款类型(0：患者本人支付，1：地服代付)
     * @param sortType          排序规则
     * @param platform          平台来源(1-运营后台, 2-花生仁，3-金琉璃，4-因子网小程序，5-因子网PC，6-因子网APP)
     * @param awardSingle       奖励标记(固定值为1，只有奖励标记查询时才传此值)
     * @param sortField         排序字段
     * @param chargeStatus      付款情况
     * @param queryType         订单列表查询类型[normal:普通订单列表;postpone:超期检测列表]
     * @param changePackage     更换套餐状态(0-待地服确认,1-已完成)
     * @param invoiceInquiry    是否已申请开票(0-否,1-是)
     * @return 分页查询结果
     */
    @GetMapping("orders")
    public ApiResult queryServantOrder(
            @RequestParam("size") int size,
            @RequestParam("page") int page,
            @RequestParam(name = "orderNo", required = false) String orderNo,
            @RequestParam(name = "groundServantName", required = false) String groundServantName,
            @RequestParam(name = "patientName", required = false) String patientName,
            @RequestParam(name = "doctorPhone", required = false) String doctorPhone,
            @RequestParam(name = "agencyName", required = false) String agencyName,
            @RequestParam(name = "sampleBarcode", required = false) String sampleBarcode,
            @RequestParam(name = "orderOrigin", required = false) String orderOrigin,
            @RequestParam(name = "sign", required = false) Integer sign,
            @RequestParam(name = "listType", required = false) String listType,
            @RequestParam(name = "status", required = false) String status,
            @RequestParam(name = "keywords", required = false) String keywords,
            @RequestParam(name = "doctorName", required = false) String doctorName,
            @RequestParam(name = "hasDcw", required = false) String hasDcw,
            @RequestParam(name = "startDate", required = false) String startDate,
            @RequestParam(name = "endDate", required = false) String endDate,
            @RequestParam(name = "orderBy", defaultValue = "0") int orderBy,
            @RequestParam(name = "payerType", required = false) String payerType,
            @RequestParam(name = "sortType", defaultValue = "asc") String sortType,
            @RequestParam(name = "platform", defaultValue = "1") Integer platform,
            @RequestParam(name = "doctorListType", defaultValue = "0") String doctorListType,
            @RequestParam(name = "doctorKeyword", required = false) String doctorKeyword,
            @RequestParam(name = "doctorId", required = false) String doctorId,
            @RequestParam(name = "awardSingle", required = false) Integer awardSingle,
            @RequestParam(name = "sortField", defaultValue = "create_date_time") String sortField,
            @RequestParam(name = "chargeStatus", required = false) String chargeStatus,
            @RequestParam(name = "changePackage", required = false) Integer changePackage,
            @RequestParam(name = "invoiceInquiry", required = false) Integer invoiceInquiry,
            @RequestParam(name = "queryType", defaultValue = "normal") String queryType,
            @FromSession UserInfo userInfo,
            HttpServletRequest request) {
        if (ClientType.PEANUT.getCode().equals(platform)) {
            GeneticTestingOrderCondition condition = new GeneticTestingOrderCondition();
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            condition.setGroundServantId(jwtInfo.getId());
            condition.setListType(listType);
            condition.setKeywords(keywords);
            condition.setStatus(status);
            condition.setDoctorName(doctorName);
            condition.setHasDcw(hasDcw);
            condition.setStartDate(startDate);
            condition.setEndDate(endDate);
            condition.setPayerType(payerType);
            condition.setDeleteFlag(0);
            OrderHelper orderHelper = OrderHelper.create(GeneticTestingOrderField.parseIntOrderBy(orderBy).getValue());
            LimitHelper limitHelper = LimitHelper.create(page, size);
            return orderService.queryServantTestingOrder(condition, orderHelper, limitHelper);
        } else if (ClientType.CONSOLE.getCode().equals(platform)) {
            LimitHelper limitHelper = LimitHelper.create(page, size);
            QueryTestingProductOrderCondition condition = new QueryTestingProductOrderCondition();
            condition.setOrderNo(orderNo);
            condition.setGroundServantName(groundServantName);
            condition.setPatientName(patientName);
            condition.setDoctorPhone(doctorPhone);
            condition.setSampleBarcode(sampleBarcode);
            condition.setStatus(status);
            condition.setStartDate(startDate);
            condition.setEndDate(endDate);
            condition.setAgencyName(agencyName);
            condition.setOrderOrigin(orderOrigin);
            condition.setSign(sign);
            condition.setAwardSingle(awardSingle);
            condition.setSortField(sortField);
            condition.setSortType(sortType);
            condition.setChargeStatus(chargeStatus);
            //套餐更换状态
            condition.setChangePackage(changePackage);
            //是否已申请开票
            condition.setInvoiceInquiry(invoiceInquiry);
            //是否查询不超期的
            condition.setIsQueryNotPostpone(1);
            if (QUERY_NORMAL_ORDER.equalsIgnoreCase(queryType)) {
                ErrorCode code = OrderController.checkSortField(sortField, sortType, condition);
                if (code != null) {
                    return ApiResult.fail(code);
                }
                return consoleOrderService.queryConsoleOrders(condition, limitHelper, sortType);
            } else {
                OrderHelper orderHelper = OrderHelper.create(sortField, "ASC".equalsIgnoreCase(sortType));
                return consoleOrderService.queryPostponeOrders(condition, orderHelper, limitHelper);
            }
        } else if (ClientType.GOLD_COLORED_GLASS.getCode().equals(platform)) {
            return orderService.queryDoctorTestingOrder(doctorId, doctorListType, doctorKeyword, LimitHelper.create
                    (page, size));
        }
        return ApiResult.fail(CommonErrorCode.CLIENT_TYPE_EXCEPTION_NOT_SUPPORTED);
    }


    /**
     * @param signDto  标记信息
     * @param orderId  订单id
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 标记/确认标记套餐
     * @author maodi
     * @createDate 2018/11/1 16:10
     */
    @PutMapping("orders/{order_id}/sign")
    public ApiResult<NullObject> sign(@RequestBody SignDto signDto, @PathVariable("order_id") String
            orderId, @FromSession UserInfo userInfo) {
        try {
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            ErrorCode code = checkSignDto(signDto, orderId);
            if (code != null) {
                return ApiResult.fail(code);
            }
            if (userInfo == null) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_ID_IS_NULL);
            }
            signDto.setSignDateTime(new Date());
            consoleOrderService.updateOrderSign(signDto, orderId, userId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.UPDATE_PACKAGE_ORDER_SIGN_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.UPDATE_PACKAGE_ORDER_SIGN_IS_ERROR);
        }
    }

    /**
     * @param signDto 标记信息
     * @param orderId 订单id
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 校验标记信息
     * @author maodi
     * @createDate 2019/1/17 9:10
     */
    private ErrorCode checkSignDto(SignDto signDto, String orderId) {
        if (signDto == null) {
            return OrderErrorCode.PACKAGE_ORDER_SIGN_IS_NULL;
        }
        Integer sign = signDto.getSignStatus();
        if (sign == null || (sign != 1 && sign != 2)) {
            return OrderErrorCode.PACKAGE_ORDER_SIGN_IS_ERROR;
        }
        GeneticTestingOrder geneticTestingOrder = orderService.findById(orderId);
        if (geneticTestingOrder == null || geneticTestingOrder.getDeleteFlag() != 0) {
            return OrderErrorCode.ORDER_NOT_EXISTED;
        }
        if (sign == 1) {
            Double doctorVal = signDto.getDoctorVal();
            if (doctorVal == null || doctorVal < 0 || doctorVal > 99) {
                return OrderErrorCode.DOCTOR_VAL_MUST_BE_0_99_INTEGER;
            }
            Double groundVal = signDto.getGroundVal();
            if (groundVal == null || groundVal < 0 || groundVal > 99) {
                return OrderErrorCode.GROUND_VAL_MUST_BE_0_99_INTEGER;
            }
            String signReason = signDto.getSignReason();
            if (StringUtils.isBlank(signReason)) {
                return OrderErrorCode.SIGN_REASON_IS_NOT_NULL;
            }
            String signProofsStr = signDto.getSignProofs();
            if (StringUtils.isBlank(signProofsStr)) {
                return OrderErrorCode.SIGN_PROOF_IS_NOT_NULL;
            }
            String[] signProofs = signProofsStr.split(",");
            if (signProofs.length > 5) {
                return OrderErrorCode.SIGN_PROOFS_MORE_THAN_5;
            }
            Integer status = geneticTestingOrder.getStatus();
            Set<Integer> set = new HashSet<Integer>() {
                {
                    add(OrderStatus.WAIT_RECEIPT_MONEY.getCode());
                    add(OrderStatus.WAIT_PERFECTED.getCode());
                    add(OrderStatus.DIFU_CONFIRMED.getCode());
                    add(OrderStatus.WAIT_SAMPLE_CONFIRM.getCode());
                    add(OrderStatus.TESTING.getCode());
                }
            };
            if (status == null || !set.contains(status)) {
                return OrderErrorCode.STATUS_MUST_BE_IN_SIGN_STATUS;
            }
        }
        return null;
    }

    /**
     * @param orderId 订单id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.dto.console.SignDto>
     * @description 根据订单id获取标记信息
     * @author maodi
     * @createDate 2019/1/17 10:57
     */
    @GetMapping("orders/{order_id}/sign/info")
    public ApiResult<SignDto> getSignInfo(@PathVariable("order_id") String orderId) {
        return ApiResult.succ(consoleOrderService.getSignInfo(orderId));
    }

    /**
     * @param lock     是否锁定(0-取消锁定，1-锁定)
     * @param orderId  订单id
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 锁定/取消锁定套餐
     * @author maodi
     * @createDate 2018/11/1 16:41
     */
    @PutMapping("orders/{order_id}/lock")
    public ApiResult<NullObject> lock(@RequestParam("is_lock") Integer lock, @PathVariable("order_id") String
            orderId, @FromSession UserInfo userInfo) {
        try {
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            if (lock == null) {
                return ApiResult.fail(OrderErrorCode.PACKAGE_ORDER_LOCK_IS_NULL);
            }
            if (lock != 0 && lock != 1) {
                return ApiResult.fail(OrderErrorCode.PACKAGE_ORDER_LOCK_IS_ERROR);
            }
            if (userInfo == null) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_ID_IS_NULL);
            }
            consoleOrderService.updateOrderLock(lock, orderId, userId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.UPDATE_PACKAGE_ORDER_LOCK_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.UPDATE_PACKAGE_ORDER_LOCK_IS_ERROR);
        }
    }

    /**
     * 获取基因检测单详情
     *
     * @param orderId 订单id
     * @return 基因检测单详情
     */
    @GetMapping("orders/{order_id}")
    public ApiResult findServantOrder(
            @PathVariable("order_id") String orderId,
            @RequestParam(name = "doctorId", required = false) String doctorId,
            @RequestParam(name = "platform", defaultValue = "1") Integer platform,
            HttpServletRequest request) {
        ClientType clientType = ClientType.getEnum(platform);
        if (ClientType.PEANUT.equals(clientType)) {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            if (StringUtils.isEmpty(jwtInfo.getId())) {
                return ApiResult.fail(OrderErrorCode.USER_INFO_IS_NOT_NULL);
            }
            return orderService.findServantTestingOrder(jwtInfo.getId(), orderId);
        } else if (ClientType.GOLD_COLORED_GLASS.equals(clientType)) {
            FieldChecker.checkEmpty(doctorId, "医生id");
            return orderService.findDoctorTestingOrder(doctorId, orderId);
        } else if (ClientType.CONSOLE.equals(clientType)) {
            return consoleOrderService.consoleOrderDetail(orderId);
        }

        return new ApiResult(500, "failed", "错误的客户端类型", null);
    }

    /**
     * 计算佣金
     *
     * @param paramDto 参数
     * @return
     */
    @PostMapping("orders/packages/commission")
    public ApiResult<OrderCommissionInfo> calculateCommission(@RequestBody CalculateCommissionParamDto paramDto) {
        if (paramDto == null) {
            return ApiResult.fail(OrderErrorCode.PARAMS_IS_NOT_NULL);
        }
        String orderId = paramDto.getOrderId();
        if (StringUtils.isEmpty(orderId)) {
            return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
        }
        if (paramDto.getCaseType() == null) {
            return ApiResult.fail(OrderErrorCode.CASE_TYPE_IS_NOT_NULL);
        }
        if (CollectionUtils.isEmpty(paramDto.getPackageIds())) {
            return ApiResult.fail(OrderErrorCode.PRODUCT_ID_IS_NOT_NULL);
        }
        //判断订单是否存在
        Integer exists = orderService.checkOrderStatus(orderId, null);
        if (exists == null) {
            return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
        }
        OrderCommissionInfo commission = orderService.calculateCommission(paramDto);
        return new ApiResult(200, "success", "增项费用和经验值查询成功", commission);
    }

    /**
     * 订单确认订单并完善信息(补全订单)-花生仁订单补全接口
     *
     * @param orderInfo 订单确认信息
     * @return
     */
    @PostMapping("orders/{order_id}/complete")
    public ApiResult postCompleteOrder(@PathVariable("order_id") String orderId,
                                       @RequestBody ReserveOrderCompleteInfo orderInfo,
                                       HttpServletRequest request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            orderInfo.setUserId(jwtInfo.getId());
            orderInfo.setUserName(jwtInfo.getUniqueName());
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            orderInfo.setOrderId(orderId);
            Integer platform = orderInfo.getPlatform();
            if (platform == null) {
                return ApiResult.fail(OrderErrorCode.PLATFORM_IS_NOT_NULL);
            }
            //校验信息是否为nul
            ErrorCode checkResult = checkParamsIsNull(orderInfo);
            if (StringUtils.isEmpty(orderInfo.getOrderNo())) {
                return ApiResult.fail(OrderErrorCode.ORDER_NUMBER_IS_NOT_NULL);
            }
            if (checkResult != null) {
                return ApiResult.fail(checkResult);
            }
            /**
             *  获取订单来源
             *  校验订单是否有效,
             *  金琉璃、花生仁的为订单待完善；
             *  商城端为新订单
             */
            Integer source = orderService.getOrderSource(orderId);
            if (source == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            orderInfo.setPlatform(source);
            Integer status = source.equals(ClientType.PEANUT.getCode()) || source.equals(ClientType
                    .GOLD_COLORED_GLASS.getCode()) ? OrderStatus.WAIT_PERFECTED.getCode() : OrderStatus.INIT.getCode();
            Integer flag = appletsOrderService.checkOrderIsEffect(orderInfo.getOrderId(), status);
            if (flag == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_STATUS_EXCEPTION);
            }
            //金琉璃订单医生不能修改
            String doctorId = orderService.checkDoctorInfo(orderInfo.getOrderId());
            if (source.equals(ClientType.GOLD_COLORED_GLASS.getCode()) && !orderInfo.getDoctorId().equals(doctorId)) {
                return ApiResult.fail(OrderErrorCode.DOCOTOR_IS_NOT_EXCHANGE);
            }
            orderInfo.setOrderId(orderId);
            return orderService.completeOrder(orderInfo, new Date());
        } catch (Exception e) {
            LOGGER.error("update Order is error", e);
            return ApiResult.fail(OrderErrorCode.UPDATE_ORDER_IS_ERROR);
        }
    }

    /**
     * @param dto     订单信息
     * @param request 请求
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.domain.reserve.CompleteOrderResultInfo>
     * @description 花生仁确认订单
     * @author maodi
     * @createDate 2018/12/19 13:57
     */
    @PutMapping("orders/{order_id}/peanut/confirm")
    public ApiResult<CompleteOrderResultInfo> peanutConfirmOrder(@RequestBody PeanutCreateAndConfirmOrderDto dto,
                                                                 HttpServletRequest request, @PathVariable("order_id")
                                                                         String orderId) {
        //校验token
        IJWTInfo jwtInfo = checkToken(request);
        if (jwtInfo == null) {
            return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
        }
        dto.setMemberId(jwtInfo.getId());
        if (StringUtils.isBlank(orderId)) {
            return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
        }
        dto.setOrderId(orderId);
        ErrorCode code = checkPeanutCreateAndConfirmOrderDto(dto);
        if (code != null) {
            return ApiResult.fail(code);
        }
        //校验订单是否有效,新订单状态值为1
        Integer flag = appletsOrderService.checkOrderIsEffect(orderId, OrderStatus.INIT.getCode());
        if (flag == null) {
            return ApiResult.fail(OrderErrorCode.ORDER_EXCEPTION);
        }
        return orderService.peanutConfirmOrder(dto);
    }

    /**
     * @param dto     订单信息
     * @param request 请求
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.domain.reserve.CompleteOrderResultInfo>
     * @description 花生仁下单
     * @author maodi
     * @createDate 2018/12/19 13:57
     */
    @PostMapping("orders/peanut/create")
    public ApiResult<CompleteOrderResultInfo> peanutCreateOrder(@RequestBody PeanutCreateAndConfirmOrderDto dto,
                                                                HttpServletRequest request) {
        //校验token
        IJWTInfo jwtInfo = checkToken(request);
        if (jwtInfo == null) {
            return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
        }
        dto.setMemberId(jwtInfo.getId());
        ErrorCode code = checkPeanutCreateAndConfirmOrderDto(dto);
        if (code != null) {
            return ApiResult.fail(code);
        }
        return orderService.peanutCreateOrder(dto);
    }

    /**
     * 地服创建基因检测订单
     *
     * @param orderInfo
     * @return
     */
    @PostMapping("orders/groudserverant")
    public ApiResult difuCreate(@RequestBody DifuCreateOrderInfoDto orderInfo, HttpServletRequest request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            orderInfo.setUserName(jwtInfo.getUniqueName());
            orderInfo.setUserId(jwtInfo.getId());
            Integer platform = orderInfo.getPlatform();
            if (platform == null) {
                return ApiResult.fail(OrderErrorCode.PLATFORM_IS_NOT_NULL);
            }
            ErrorCode checkResult = checkParamsIsNull(orderInfo);
            if (checkResult != null) {
                return ApiResult.fail(checkResult);
            }
            return orderService.createOrder(orderInfo, new Date());
        } catch (Exception e) {
            LOGGER.error("difu create Order is error", e);
            return ApiResult.fail(OrderErrorCode.ADD_ORDER_IS_ERROR);
        }
    }

    /**
     * 判断订单状态是否已付款
     *
     * @param orderId 订单id
     * @param request
     * @return
     */
    @GetMapping("orders/status/{order_id}")
    public ApiResult checkOrderIsPay(@PathVariable("order_id") String orderId, HttpServletRequest request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            //判断订单是否存在
            Integer exists = orderService.checkOrderStatus(orderId, null);
            if (exists == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            //判断订单是否付款
            Integer flag = orderService.checkOrderIsPay(orderId);
            if (flag == null || flag == 0) {
                return new ApiResult(200, "success", "订单已付款", true);
            }
            return new ApiResult(200, "success", "订单未付款", false);
        } catch (Exception e) {
            LOGGER.error("query order status is error", e);
            return ApiResult.fail(OrderErrorCode.QUERY_ORDER_STATUS_EXCEPTION);
        }
    }

    /**
     * 患者付款后确认订单
     *
     * @param confirmedInfo 确认信息
     * @param request
     * @return
     */
    @PostMapping("orders/confirmed")
    public ApiResult orderConfirmed(@RequestBody PatientConfirmedInfo confirmedInfo, HttpServletRequest request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            //判断订单是否存在
            Integer exists = orderService.checkOrderStatus(confirmedInfo.getOrderId(), null);
            if (exists == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            String type = confirmedInfo.getTestingApplyType();
            if (StringUtils.isEmpty(type)) {
                return ApiResult.fail(OrderErrorCode.ORDER_TEST_APPLY_IS_NOT_NULL);
            }
            if ("0".equals(type) && StringUtils.isEmpty(confirmedInfo.getTestingPhoto())) {
                return ApiResult.fail(OrderErrorCode.ORDER_TEST_IMAGE_IS_NOT_NULL);
            }
            //患者付款后确认订单
            orderService.updateOrderTestInfo(confirmedInfo);
            return new ApiResult(200, "success", "确认订单成功", null);
        } catch (Exception e) {
            LOGGER.error("confirmed order is error", e);
            return ApiResult.fail(OrderErrorCode.ORDER_CONFIRMED_EXCEPTION);
        }
    }

    /**
     * @param orderNo        订单编号
     * @param orderCancelDto 取消原因
     * @param request        请求
     * @return com.hsgene.common.util.result.ApiResult
     * @description 取消基因检测单
     * @author maodi
     * @createDate 2018/9/29 9:41
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PutMapping("orders/{order_no}/cancel")
    public ApiResult<NullObject> cancelOrder(@PathVariable("order_no") String orderNo, @RequestBody OrderCancelDto
            orderCancelDto, HttpServletRequest request) {
        try {
            Integer platform = orderCancelDto.getPlatform();
            if (platform == null) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.PLATFORM_IS_NOT_NULL);
            }
            if (!ClientType.PEANUT.getCode().equals(platform) && !ClientType.GOLD_COLORED_GLASS.getCode().equals
                    (platform)) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.PLATFORM_IS_ERROR);
            }
            Integer cancelType = orderCancelDto.getCancelType();
            String userId;
            if (ClientType.GOLD_COLORED_GLASS.getCode().equals(platform)) {
                userId = orderCancelDto.getUserId();
                if (StringUtils.isBlank(userId)) {
                    return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_ID_IS_NULL);
                }
                if (cancelType == null) {
                    return ApiResult.fail(OrderErrorCode.CANCEL_TYPE_IS_NOT_NULL);
                }
            } else if (ClientType.PEANUT.getCode().equals(platform)) {
                //校验token
                IJWTInfo jwtInfo = checkToken(request);
                if (jwtInfo == null) {
                    return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
                }
                userId = jwtInfo.getId();
                if (StringUtils.isBlank(userId)) {
                    return ApiResult.fail(OrderErrorCode.USER_INFO_IS_NOT_NULL);
                }
            }
            if (cancelType != null) {
                if (cancelType != 1 && cancelType != 2 && cancelType != 3 && cancelType != 4) {
                    return ApiResult.fail(OrderErrorCode.CANCEL_TYPE_IS_ERROR);
                }
            }
            String cancelReason = orderCancelDto.getCancelReason();
            if (StringUtils.isBlank(orderNo)) {
                return ApiResult.fail(OrderErrorCode.ORDER_NO_IS_NOT_NULL);
            }
            if (StringUtils.isNotBlank(cancelReason)) {
                if (cancelReason.length() > 200) {
                    return ApiResult.fail(OrderErrorCode.CANCEL_REASON_EXCEED_200);
                }
            }
            GeneticTestingOrder geneticTestingOrder = orderService.findByOrderNo(orderNo);
            if (geneticTestingOrder == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NO_IS_NOT_EXIST);
            }
            String id = geneticTestingOrder.getId();
            if (StringUtils.isBlank(id)) {
                return ApiResult.fail(OrderErrorCode.ORDER_NO_IS_NOT_EXIST);
            }
            orderService.cancelOrder(id, cancelReason, cancelType);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error("cancel order is error", e);
            return ApiResult.fail(OrderErrorCode.TESTING_ORDER_CANCEL_IS_ERROR);
        }
    }

    /**
     * @param orderId 订单id
     * @param request 请求
     * @return com.hsgene.common.util.result.ApiResult
     * @description 获取基因检测单基础信息
     * @author maodi
     * @createDate 2018/9/29 15:25
     */
    @GetMapping("orders/{order_id}/base/info")
    public ApiResult<BaseInfoDataDto> getBaseInfoById(@PathVariable("order_id") String orderId, HttpServletRequest
            request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            if (StringUtils.isBlank(jwtInfo.getId())) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            BaseInfoDataDto data = orderService.getBaseInfoById(orderId);
            return ApiResult.succ(data);
        } catch (Exception e) {
            LOGGER.error("get base info is error", e);
            return ApiResult.fail(OrderErrorCode.GET_BASE_INFO_IS_ERROR);
        }
    }

    /**
     * 地服完善快递、耗材信息(完善订单-二次补全)-花生仁订单完善接口
     *
     * @param difuCompete 信息对象
     * @return
     */
    @PutMapping("orders/{order_id}/express")
    public ApiResult difuComplete(@PathVariable("order_id") String orderId,
                                  @RequestBody DifuCompeteOrderInfoDto difuCompete,
                                  HttpServletRequest request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            if (StringUtils.isEmpty(jwtInfo.getId())) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            ErrorCode code = checkDifuCompleteParamIsNull(difuCompete);
            if (code != null) {
                return ApiResult.fail(code);
            }
            difuCompete.setOrderId(orderId);
            /*//校验订单状态是否是已存款订单
            Integer flag = orderService.checkOrderStatus(difuCompete.getOrderId(), OrderStatus.WAIT_PERFECTED.getCode
                    ());*/
            //校验订单状态是否待地管确认、待确认样本、报告待上传、报告待审核状态
            Integer flag = orderService.checkSecondPerfectOrderStatus(difuCompete.getOrderId());
            if (flag == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_STATUS_EXCEPTION);
            }
            String result = orderService.difuComplete(difuCompete, jwtInfo.getId());
            if (result == null) {
                return new ApiResult(200, "success", "订单完善成功", null);
            }
            LOGGER.error("order second complete is error...");
            return ApiResult.fail(OrderErrorCode.GOODS_AMOUNT_IS_TO_MANY, result);
        } catch (Exception e) {
            LOGGER.error("difu complete order info is error", e);
            return ApiResult.fail(OrderErrorCode.UPDATE_ORDER_IS_ERROR);
        }
    }

    /**
     * 同步检测申请单信息
     *
     * @param orderId
     * @return
     */
    @PutMapping("orders/{order_id}/sync/requisitions")
    public ApiResult synTestOrder(@PathVariable("order_id") String orderId) {
        try {
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_NUMBER_IS_NOT_NULL);
            }
            orderService.synTestOrder(orderId);
            return ApiResult.succ(null, "检测单信息同步成功");
        } catch (Exception e) {
            LOGGER.error("syn TestOrder is error", e);
            return ApiResult.fail(OrderErrorCode.SYN_TESTORDER_IS_ERROR);
        }
    }

    /**
     * 上传dcw信息
     *
     * @param dcwInfoDto 上传dcw信息
     * @return
     */
    @PostMapping("orders/{order_id}/dcw")
    public ApiResult uploadDcw(@PathVariable("order_id") String orderId,
                               @RequestBody UploadDcwDetailsDto dcwInfoDto) {
        try {
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            dcwInfoDto.setOrderId(orderId);
            String result = checkDcwIsEmpty(dcwInfoDto);
            if (result != null) {
                return new ApiResult(60001, "failed", result, null);
            }
            return orderService.uploadDcw(dcwInfoDto);
        } catch (Exception e) {
            LOGGER.error("upload dcw is error", e);
            return ApiResult.fail(OrderErrorCode.DCW_UPLOAD_IS_ERROR);
        }
    }

    /**
     * 获取dcw信息
     *
     * @param orderId
     * @return
     */
    @GetMapping("orders/dcw/{order_id}")
    @IgnoreUserToken
    public ApiResult getDcwInfos(@PathVariable("order_id") String orderId, HttpServletRequest request) {
        try {
            //校验token
//            IJWTInfo jwtInfo = checkToken(request);
//            if (jwtInfo == null) {
//                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
//            }
            LOGGER.info("get dcw info...");
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            Integer flag = orderService.checkOrderStatus(orderId, null);
            if (flag == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            DcwImageModel imageModel = orderService.getDcwInfos(orderId);
            return new ApiResult(200, "success", "获取dcw信息成功", imageModel);
        } catch (Exception e) {
            LOGGER.error("query dcw info is error...", e);
            return ApiResult.fail(OrderErrorCode.QUERY_DCW_INFO_IS_ERROR);
        }
    }

    private IJWTInfo checkToken(HttpServletRequest request) {
        try {
            String authorization = request.getHeader("Authorization");
            if (StringUtils.isBlank(authorization)) {
                authorization = request.getHeader("authorization");
            }
            return jwtToken.getInfoFromToken(authorization);
        } catch (Exception e) {
            LOGGER.error("Authorization-Token解析异常：", e);
            return null;
        }
    }

    /**
     * 申请录入
     *
     * @param orderId 订单ID
     * @return
     */
    @PutMapping("orders/{order_id}/dcw")
    public ApiResult applicationEntry(@PathVariable("order_id") String orderId) {
        try {
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_NUMBER_IS_NOT_NULL);
            }
            return orderService.applicationEntry(orderId);
        } catch (Exception e) {
            LOGGER.error("application Entry is error", e);
            return ApiResult.fail(OrderErrorCode.ENTRY_IS_ERROR);
        }
    }

    /**
     * 发放积分
     *
     * @param orderId 订单id
     * @return
     */
    @PutMapping("orders/{order_id}/sendpoint")
    public ApiResult sendPoint(@PathVariable("order_id") String orderId) {
        try {
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            //判断订单是否标记
            Integer isSign = orderService.checkOrderIsSign(orderId);
            /*if (isSign == null || isSign == 0) {
                return ApiResult.fail(OrderErrorCode.ORDER_IS_NOT_SIGN);
            }*/
            if (isSign != null && isSign == 1) {
                return ApiResult.fail(OrderErrorCode.ORDER_SIGN_IS_NOT_CONFIRM);
            }
            //判断订单是否有发放积分权限
            Integer flag = orderService.checkPointSend(orderId);
            if (flag == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            //判断订单积分状态是否是未发放
            Integer status = orderService.checkPointSendStatus(orderId);
            if (status != null) {
                //发放积分
                Boolean result = orderService.sendPoint(orderId);
                if (result) {
                    return new ApiResult(200, "success", "订单发放积分申请成功", result);
                }
            }
            //积分已发放提示
            return ApiResult.fail(OrderErrorCode.ORDER_POINT_IS_SEND);
        } catch (Exception e) {
            LOGGER.error("send point is error...", e);
            return ApiResult.fail(OrderErrorCode.ORDER_POINT_IS_ERROR);
        }
    }

    /**
     * 确认收件
     *
     * @param receiptDto 参数
     * @return
     */
    @PutMapping("orders/{order_id}/confirmation/receipt")
    public ApiResult confirmReceipt(@PathVariable("order_id") String orderId, @RequestBody OrderConfirmReceiptDto
            receiptDto) {
        try {
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_NUMBER_IS_NOT_NULL);
            }
            if (receiptDto.getExpressIds() == null || receiptDto.getExpressIds().isEmpty()) {
                return ApiResult.fail(OrderErrorCode.CONFIRMED_INFO_IS_NOT_NULL);
            }
            receiptDto.setOrderId(orderId);
            return orderService.confirmReceipt(receiptDto);
        } catch (Exception e) {
            LOGGER.error("confirm receipt is error", e);
            return ApiResult.fail(OrderErrorCode.CONFIRMED_RECEIPT_IS_ERROR);
        }
    }

    /**
     * 花生仁确认报告(地服审核报告)
     *
     * @param orderPackageDetailId
     * @return
     */
    @PutMapping("orders/packages/reports/{report_id}")
    public ApiResult confirmReport(@PathVariable("report_id") String orderPackageDetailId, @RequestBody
            OrderPackageDetail orderPackageDetail) {
        orderPackageDetail.setId(orderPackageDetailId);
        if (StringUtils.isEmpty(orderPackageDetailId)) {
            return ApiResult.fail(OrderErrorCode.ORDER_NUMBER_IS_NOT_NULL);
        }
        return orderService.updateReportStatus(orderPackageDetail);
    }


    @Resource
    GeneratorService generatorService;

    @Resource
    MessageService messageService;

    @Value("${sms.timeout}")
    private int smsTimeout;

    /**
     * @param patientInfoConfirm 患者信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 患者信息确认
     * @author maodi
     * @createDate 2018/9/30 14:23
     */
    @IgnoreUserToken
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PutMapping("orders/{order_id}/patient/confirmation")
    public ApiResult patientInfoConfirm(@RequestBody PatientInfoConfirmDto patientInfoConfirm) {
        try {
            ErrorCode code = checkPatientInfoConfirmParamIsNull(patientInfoConfirm);
            if (code != null) {
                return ApiResult.fail(code);
            }
            String id = patientInfoConfirm.getId();
            //验证验证码是否正确
            Object obj = messageService.getVerifyCodeByPhone(patientInfoConfirm.getMobile());
            if (obj == null || obj instanceof ApiResult) {
                return ApiResult.fail(OrderErrorCode.PATIENT_INFO_CONFIRM_IS_ERROR);
            }
            if (obj instanceof Map) {
                Map<String, Object> verifyCodeMap = (Map<String, Object>) obj;
                String sendTimeStr = String.valueOf(verifyCodeMap.get("sendTime").toString());
                Date date = SimpleDateUtils.getSimpleDateFormat(SimpleDateUtils.DatePattern.STANDARD_PATTERN.toString())
                        .parse(sendTimeStr);
                sendTimeStr = SimpleDateUtils.dateToTimestamp(SimpleDateUtils.dateFormatToStr(date));
                long currentTime = System.currentTimeMillis();
                long sendTime = Long.valueOf(sendTimeStr);
                if (currentTime - sendTime > smsTimeout || sendTime > currentTime) {
                    return ApiResult.fail(OrderErrorCode.VERIFY_CODE_IS_TIME_OUT);
                }
                GeneratorDto data = generatorService.getGenerator("sms", "").getData();
                int length = data.getSerialNumber().length();
                String verifyCode = String.valueOf(verifyCodeMap.get("verifyCode")).substring(0, length);
                if (!patientInfoConfirm.getVerification().equals(verifyCode)) {
                    return ApiResult.fail(OrderErrorCode.PATIENT_INFO_CONFIRM_VERIFICATION_IS_ERROR);
                }
            }
            //修改患者的确认标识
            orderService.updatePatientInfoConfirm(id);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.CONFIRM_PATIENT_INFO_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.PATIENT_INFO_CONFIRM_IS_ERROR);
        }
    }


    @IgnoreUserToken
    @PostMapping("orders/sendMessage")
    public ApiResult sendMessageToPhone(String phone) {
        try {
            if (StringUtils.isBlank(phone) || !SimpleRegexUtils.isMobile(phone)) {
                return ApiResult.fail(CommonErrorCode.PHONE_INVALIDATION_FORMAT);
            }
            GeneratorDto data = generatorService.getGenerator("sms", "").getData();
            String verifyCode = data.getSerialNumber();
            messageService.sendMessage(verifyCode + ".此验证码仅用于患者确认，验证码提供给他人会泄露您的账号信息，请勿转发。【华生基因】", phone);
            return ApiResult.succ();
        } catch (Exception e) {
            return ApiResult.fail(OrderErrorCode.VERIFY_CODE_SEND_IS_ERROR);
        }
    }

    private ErrorCode checkPatientInfoConfirmParamIsNull(PatientInfoConfirmDto patientInfoConfirm) {
        if (patientInfoConfirm == null) {
            return OrderErrorCode.PATIENT_INFO_CONFIRM_IS_NULL;
        }
        if (StringUtils.isBlank(patientInfoConfirm.getId())) {
            return OrderErrorCode.PATIENT_INFO_CONFIRM_ID_IS_NULL;
        }
        if (StringUtils.isBlank(patientInfoConfirm.getAction())) {
            return OrderErrorCode.PATIENT_INFO_CONFIRM_ACTION_IS_NULL;
        }
        if (StringUtils.isBlank(patientInfoConfirm.getMobile())) {
            return OrderErrorCode.PATIENT_INFO_CONFIRM_MOBILE_IS_NULL;
        }
        if (StringUtils.isBlank(patientInfoConfirm.getVerification())) {
            return OrderErrorCode.PATIENT_INFO_CONFIRM_VERIFICATION_IS_NULL;
        }
        return null;
    }

    private String checkDcwIsEmpty(UploadDcwDetailsDto dcwInfoDto) {
        if (dcwInfoDto == null) {
            return "dcw信息不能为空";
        }
        try {
            Field[] field = dcwInfoDto.getClass().getDeclaredFields();
            for (Field f : field) {
                f.setAccessible(true);
                String name = f.getName();
                String value = (String) f.get(dcwInfoDto);
                if (!"id".equals(name) && StringUtils.isEmpty(value)) {
                    return UploadDcwEnum.getEnum(f.getName()) + "信息不存在";
                }
            }
        } catch (Exception e) {
            LOGGER.error("object attribute is not null", e);
        }
        return null;
    }


    /**
     * 根据id获取检测申请单信息
     *
     * @param requistionId 申请单id
     * @return
     */
    @GetMapping("requistions/{requistion_id}")
    public ApiResult requistions(@PathVariable("requistion_id") String requistionId) {
        try {
            return orderService.requistions(requistionId);
        } catch (Exception e) {
            LOGGER.error("requistion info by id is error", e);
            e.printStackTrace();
            return new ApiResult(500, "failed", "数据获取失败", e.toString());
        }
    }

    private ErrorCode checkDifuCompleteParamIsNull(DifuCompeteOrderInfoDto difuCompete) {
        if (difuCompete == null) {
            return OrderErrorCode.UPDATE_ORDER_IS_ERROR;
        }
        //校验参数
        List<GeneticTestingExpressDeliveryDto> expressDeliveryDtos = difuCompete.getExpressDeliveryInfo();
        if (expressDeliveryDtos != null && !expressDeliveryDtos.isEmpty()) {
            for (GeneticTestingExpressDeliveryDto deliveryDto : expressDeliveryDtos) {
                if (StringUtils.isEmpty(deliveryDto.getPackageId())) {
                    return OrderErrorCode.PRODUCT_IS_NOT_NULL;
                }
                if (!deliveryDto.getExpressCompany().contains("人工物流") && !deliveryDto.getExpressCompany().contains
                        ("rgwl")) {
                    if (StringUtils.isEmpty(deliveryDto.getExpressNo())) {
                        return OrderErrorCode.EXPRESS_DELIVERY_IS_NOT_NULL;
                    }
                    if (StringUtils.isEmpty(deliveryDto.getExpressCompany())) {
                        return OrderErrorCode.EXPRESS_COMPANY_IS_NOT_NULL;
                    }
                }
                if (deliveryDto.getCourierDateTime() == null) {
                    return OrderErrorCode.EXPRESS_DATE_IS_NOT_NULL;
                }
            }
        }
        String expressImages = difuCompete.getExpressReturnImages();
        /*if (StringUtils.isEmpty(expressImages)) {
            return OrderErrorCode.EXPRESS_RETURN_IMAGE_IS_NOT_NULL;
        }*/
        if (StringUtils.isNotEmpty(expressImages) && expressImages.split(CharactersConstant.COMMA_EN).length > 5) {
            return OrderErrorCode.EXPRESS_RETURN_IMAGE_IS_LONG;
        }
        String sampleImages = difuCompete.getSampleImages();
//        if (StringUtils.isEmpty(expressImages)) {
//            return OrderErrorCode.IMAGE_IS_NOT_NULL;
//        }
        if (StringUtils.isNotEmpty(expressImages) && sampleImages.split(CharactersConstant.COMMA_EN).length > 5) {
            return OrderErrorCode.IMAGE_COUNT_IS_LONG;
        }
        //耗材
        List<GeneticOrderGoodsInfoDto> goodsInfoDtos = difuCompete.getProductInfoList();
        if (goodsInfoDtos == null || goodsInfoDtos.isEmpty()) {
            //return OrderErrorCode.CONSUMABLES_IS_NOT_NULL;
            return null;
        }
        for (GeneticOrderGoodsInfoDto goodsInfo : goodsInfoDtos) {
            if (StringUtils.isEmpty(goodsInfo.getGoodsId())) {
                return OrderErrorCode.CONSUMABLES_ID_IS_NOT_NULL;
            }
            if (goodsInfo.getUsageAmount() == null) {
                return OrderErrorCode.CONSUMABLES_CCOUNT_IS_NOT_NULL;
            }
            if (goodsInfo.getUsageAmount() == 0) {
                return OrderErrorCode.CONSUMABLES_CCOUNT_IS_NOT_ZERO;
            }
        }
        return null;
    }

    private ErrorCode checkPeanutCreateAndConfirmOrderDto(PeanutCreateAndConfirmOrderDto dto) {
        Double totalCharges = dto.getTotalCharges();
        if (totalCharges == null || totalCharges == 0) {
            return OrderErrorCode.TOTAL_MONEY_IS_NOT_NULL;
        }
        if (totalCharges <= 0) {
            return OrderErrorCode.TOTAL_MONEY_MUST_BE_POSITIVE_NUMBER;
        }
        String patientName = dto.getPatientName();
        if (StringUtils.isBlank(patientName)) {
            return OrderErrorCode.PATIENT_NAME_IS_NOT_NULL;
        }
        Integer payerType = dto.getPayerType();
        if (payerType == null) {
            return OrderErrorCode.PAY_TYPE_IS_NOT_NULL;
        }
        if (payerType != 0 && payerType != 1) {
            return OrderErrorCode.PAY_TYPE_IS_ERROR;
        }
        return null;
    }

    private ErrorCode checkParamsIsNull(DifuCreateOrderInfoDto orderInfoDto) throws IllegalAccessException,
            NoSuchFieldException {
        if (orderInfoDto == null) {
            return OrderErrorCode.DATA_INFO_IS_NOT_NULL;
        }
        if (StringUtils.isEmpty(orderInfoDto.getUserId()) || StringUtils.isEmpty(orderInfoDto.getUserName())) {
            return OrderErrorCode.USER_INFO_IS_NULL;
        }
        Integer payType = orderInfoDto.getPayerType();
        if (payType == null) {
            return OrderErrorCode.PAY_TYPE_IS_NOT_NULL;
        }
        if (payType != 0 && payType != 1) {
            return OrderErrorCode.PAY_TYPE_IS_ERROR;
        }
        if (orderInfoDto.getPlatform() == null || orderInfoDto.getPlatform() == 0) {
            return AppletsOrderErrorCode.ORDER_SOURCE_IS_NOT_NULL;
        }
        if (StringUtils.isEmpty(orderInfoDto.getDoctorId())) {
            return OrderErrorCode.DOCOTOR_ID_IS_NOT_NULL;
        }
        if (orderInfoDto.getTotalCharges() == null || orderInfoDto.getTotalCharges() == 0 || orderInfoDto
                .getTotalCommissions() == null) {
            return OrderErrorCode.TOTAL_MONEY_IS_NOT_NULL;
        }
        GeneticCompletePatientInfo patientInfo = orderInfoDto.getPatientInfo();
        if (patientInfo == null) {
            return OrderErrorCode.PATIENT_IS_NOT_NULL;
        }
        if (StringUtils.isEmpty(patientInfo.getPatientName())) {
            return OrderErrorCode.PATIENT_NAME_IS_NOT_NULL;
        }
        if (patientInfo.getPatientSex() == null) {
            return OrderErrorCode.PATIENT_SEX_IS_NOT_NULL;
        }
        if (patientInfo.getPatientAge() == null) {
            return OrderErrorCode.PATIENT_AGE_IS_NOT_NULL;
        }
        if (StringUtils.isEmpty(patientInfo.getPatientPhoneNumber())) {
            return OrderErrorCode.PATIENT_PHONE_IS_NOT_NULL;
        }
        if (StringUtils.isEmpty(orderInfoDto.getTestingPurpose())) {
            return OrderErrorCode.TEST_PURPOSE_IS_NOT_NULL;
        }
        if (patientInfo.isPastFlag()) {
            if (StringUtils.isEmpty(patientInfo.getPastItem()) || StringUtils.isEmpty(patientInfo.getPastResult())) {
                return OrderErrorCode.TEST_PURPOSE_IS_NOT_NULL;
            }
        }

        List<GeneticCompleteDisease> diseaseList = orderInfoDto.getDiseaseList();
        if (diseaseList == null || diseaseList.isEmpty()) {
            return OrderErrorCode.DISEASE_IS_NOT_NULL;
        }
        for (GeneticCompleteDisease disease : diseaseList) {
            String result = ObjectAttrUtils.checkObjectAttrIsNull(disease, null);
            if (StringUtils.isNotEmpty(result)) {
                return ObjectAttributeInfoEnum.getEnum(result);
            }
        }
        if (StringUtils.isEmpty(orderInfoDto.getClinicalDiagnosis())) {
            return OrderErrorCode.CLINICAL_DIAGNOSIS_IS_NOT_NULL;
        }
        if (StringUtils.isEmpty(orderInfoDto.getCaseType())) {
            return OrderErrorCode.CASE_TYPE_IS_NOT_NULL;
        }
        String images = orderInfoDto.getImages();
        /*if (StringUtils.isEmpty(images)) {
            return OrderErrorCode.IMAGE_IS_NOT_NULL;
        }*/
        if (StringUtils.isNotEmpty(images) && images.split(CharactersConstant.COMMA_EN).length > 5) {
            return OrderErrorCode.IMAGE_COUNT_IS_LONG;
        }
        List<OrderCompleteProductInfo> productInfoList = orderInfoDto.getProductInfoList();
        if (productInfoList == null || productInfoList.isEmpty()) {
            return OrderErrorCode.PRODUCT_IS_NOT_NULL;
        }
        for (OrderCompleteProductInfo productInfo : productInfoList) {
            //判断样本
            String sampleIds = productInfo.getSampleId();
            if (StringUtils.isEmpty(sampleIds)) {
                return ObjectAttributeInfoEnum.getEnum("sampleId");
            }
            String[] arrays = sampleIds.split(CharactersConstant.COMMA_EN);
            for (String sampleId : arrays) {
                //获取label_key
                String paramsKey = orderService.checkParamsIsNull(sampleId);
                if (StringUtils.isEmpty(paramsKey)) {
                    continue;
                }
                //labelKey拆分
                String[] labelKeys = paramsKey.split(CharactersConstant.COMMA_EN);
                for (String index : labelKeys) {
                    //获取参数名
                    String paramName = sampleMap.get(index);
                    if (StringUtils.isEmpty(paramName)) {
                        continue;
                    }
                    //判断value
                    Field field = productInfo.getClass().getDeclaredField(paramName);
                    field.setAccessible(true);
                    Object value = field.get(productInfo);
                    if (ObjectUtils.isEmpty(value)) {
                        return ObjectAttributeInfoEnum.getEnum(paramName);
                    }
                }
            }
            List<Object> excludeFields = ObjectAttrUtils.getExcludeObjectFields("remarks", "hospitalCode",
                    "whiteCount", "sendWaxBlock", "agencyCode", "bloodSampleImages", "expressCompany", "expressNo",
                    "courierDateTime", "expressRemarks", "cost");
            String result = ObjectAttrUtils.checkObjectAttrIsNull(productInfo, excludeFields);
            if (StringUtils.isNotEmpty(result)) {
                return ObjectAttributeInfoEnum.getEnum(result);
            }
        }

        //判断存在耗材信息时,数量必填
        List<GeneticOrderGoodsInfoDto> goodsInfoDtos = orderInfoDto.getGoodsInfoList();
        if (goodsInfoDtos != null && !goodsInfoDtos.isEmpty()) {
            for (GeneticOrderGoodsInfoDto goodsInfo : goodsInfoDtos) {
                if (goodsInfo.getUsageAmount() == null || goodsInfo.getUsageAmount() == 0
                        || StringUtils.isEmpty(goodsInfo.getGoodsId())) {
                    return OrderErrorCode.CONSUMABLES_IS_NOT_NULL;
                }
            }
        }
        return null;
    }

    /**
     * 根据基因检测单id获取检测申请单信息列表
     *
     * @param orderId 订单id
     * @param orgIds  检测机构ids(逗号分隔)
     * @return 检测申请单信息列表
     */
    @GetMapping("orders/{order_id}/requistions")
    public ApiResult<List<OrderRequisitionDto>> getRequisitionInfoByOrderId(
            @PathVariable("order_id") String orderId,
            @RequestParam(name = "orgIds", required = false) String orgIds) {
        return orderService.getRequisitionInfoByOrderId(orderId, orgIds);
    }

    /**
     * 基因检测单套餐变更记录分页查询
     *
     * @param page 页码
     * @param size 分页大小(默认值:10)
     * @return 查询结果
     */
    @GetMapping("orders/packages/interchange")
    public ApiResult<Pagination<OrderInterchangeListDto>> pageInterChange(
            @RequestParam("page") int page,
            @RequestParam("size") int size,
            HttpServletRequest request) {
        //校验token
        IJWTInfo jwtInfo = checkToken(request);
        if (jwtInfo == null) {
            return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
        }
        if (StringUtils.isEmpty(jwtInfo.getId())) {
            return ApiResult.fail(OrderErrorCode.USER_INFO_IS_NOT_NULL);
        }
        return orderService.pageInterchange(jwtInfo.getId(), page, size);
    }

    /**
     * 查询基因检测单套餐变更记录信息
     *
     * @param interchangeId 变更记录id
     * @return 基因检测单套餐变更记录信息
     */
    @GetMapping("orders/packages/interchange/{interchange_id}")
    public ApiResult<OrderInterChangeDetailDto> interChangeInfo(@PathVariable("interchange_id") String interchangeId) {
        return orderService.interChangeInfo(interchangeId);
    }

    /**
     * 处理套餐变更
     * 原API：/api/gene/geneOrder/completeInterChange
     *
     * @return 处理变更结果
     */
    @PutMapping("orders/packages/interchange/{interchange_id}")
    public ApiResult<String> completeInterchange(
            @PathVariable("interchange_id") String interchangeId,
            @RequestBody GeneOrderInterchange interchange, HttpServletRequest request) {
        interchange.setId(interchangeId);
        IJWTInfo jwtInfo = checkToken(request);
        if (jwtInfo == null) {
            return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
        }

        return orderService.completeInterchange(interchange, jwtInfo.getId());
    }

    /**
     * 删除订单
     *
     * @param orderId 订单id
     * @param request
     * @return
     */
    @DeleteMapping("orders/{order_id}")
    public ApiResult deleteOrderId(@PathVariable("order_id") String orderId, HttpServletRequest request) {
        try {
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            //判断订单是否存在
            Integer exists = orderService.checkOrderStatus(orderId, null);
            if (exists == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            orderService.deleteOrderId(orderId);
            return new ApiResult(200, "success", "订单删除成功", null);
        } catch (Exception e) {
            LOGGER.error("delete order is error...", e);
            return ApiResult.fail(OrderErrorCode.ORDER_DELETE_IS_ERROR);
        }
    }

    /**
     * 基因检测单收款(地服代付: confirm_order_cheques)
     *
     * @param orderRequest 基因检测单收款(地服代付请求信息)
     * @return 支付信息
     */
    @PostMapping("/orders/{order_id}/payment")
    public ApiResult<String> difuPayProcessOrder(
            @RequestBody TestingOrderRequestDto orderRequest) {
        return orderService.difuPayProcessOrder(orderRequest);
    }

    /**
     * 套餐变更补款付款
     *
     * @param interChangeId 变更id
     * @param payMethod     支付方式
     * @return 支付信息
     */
    @GetMapping("orders/{order_id}/interchange/{interchange_id}/payment")
    public ApiResult<String> interChangeRepaid(
            @PathVariable("interchange_id") String interChangeId,
            @RequestParam(name = "payMethod", defaultValue = "ALIPAY_MOBILE") String payMethod) {
        return orderService.interChangeRepaid(interChangeId, payMethod);
    }

    /**
     * 获取订单关联的字典项目或枚举
     *
     * @param platform 请求方标识
     * @param type     字典项目或枚举类型
     * @return
     */
    @GetMapping("orders/dict")
    public ApiResult<Map<String, List<CommonDictDto>>> queryOrderDict(
            @RequestParam(name = "platform", defaultValue = "2") Integer platform,
            @RequestParam(name = "type", defaultValue = "order_status") String type) {
        ClientType clientType = ClientType.getEnum(platform);
        return ApiResult.succ(orderService.queryDict(clientType, type));
    }

    @PutMapping("orders/{order_id}/sign/express")
    public ApiResult<NullObject> signExpress() {
        return ApiResult.fail(OrderErrorCode.PEANUT_SIGN_EXPRESS);
    }

    /**
     * 地服发货
     *
     * @param expressDelivery
     * @return
     * @author FX
     * @date 2018/11/14 11:19
     */
    @PostMapping("order/{order_id}/ship")
    public ApiResult groundDelivery(@PathVariable("order_id") String orderId, @RequestBody
            GeneticTestingExpressDelivery expressDelivery) {
        expressDelivery.setOrderId(orderId);
        return orderService.groundDelivery(expressDelivery);
    }

    /**
     * @param orderId  订单id
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 将订单首单奖励状态改为已奖励
     * @author maodi
     * @createDate 2018/11/26 15:03
     */
    @PutMapping("orders/{order_id}/awarded")
    public ApiResult<NullObject> awarded(@PathVariable("order_id") String orderId, @FromSession UserInfo userInfo) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_ID_IS_NULL);
            }
            orderService.awarded(orderId, userId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.AWARDED_SINGLE_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.AWARDED_SINGLE_IS_ERROR);
        }
    }

    /**
     * @param orderId 订单id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.order.dto.console.OrderUpdateRealPriceDto>
     * @description 根据id获取订单实际价格信息
     * @author maodi
     * @createDate 2018/11/28 11:07
     */
    @GetMapping("orders/real/price/{order_id}")
    public ApiResult<OrderUpdateRealPriceDto> queryRealPrice(@PathVariable("order_id") String orderId) {
        try {
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            Integer orderOrigin = orderService.queryOrderOrigin(orderId);
            if (orderOrigin == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            if (!ClientType.PEANUT.getCode().equals(orderOrigin) && !ClientType.GOLD_COLORED_GLASS.getCode().equals
                    (orderOrigin)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ORIGIN_MUST_BE_PEANUT_OR_GOLD_COLORED_GLASS);
            }
            ApiResult<OrderBaseInfo> apiResult = consoleOrderService.consoleOrderDetail(orderId);
            ErrorCode code = apiResult.getError();
            if (code != null) {
                return ApiResult.fail(code);
            }
            OrderBaseInfo baseInfo = apiResult.getData();
            if (baseInfo == null) {
                return ApiResult.fail(OrderErrorCode.GET_PLATFORM_ORDER_DETAILS_IS_ERROR);
            }
            OrderUpdateRealPriceDto dto = orderService.queryUpdateRealPriceDto(orderId);
            dto.setTotalCharges(baseInfo.getReceivablePrice().doubleValue());
            return ApiResult.succ(dto);
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.QUERY_ORDER_UPDATE_REAL_PRICE_BY_ORDER_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.QUERY_ORDER_UPDATE_REAL_PRICE_BY_ORDER_ID_IS_ERROR);
        }
    }

    /**
     * @param dto      套餐实际价格信息
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.result.NullObject>
     * @description 修改订单套餐实收价格(特殊价格)
     * @author maodi
     * @createDate 2018/11/28 11:07
     */
    @PutMapping("orders/packages/real/price")
    public ApiResult<NullObject> updatePackagePrice(@RequestBody OrderUpdateRealPriceDto dto, @FromSession UserInfo
            userInfo) {
        try {
            if (dto == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_REAL_PRICE_DTO_IS_NOT_NULL);
            }
            String orderId = dto.getOrderId();
            if (StringUtils.isBlank(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            Integer orderOrigin = orderService.queryOrderOrigin(orderId);
            if (orderOrigin == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            if (!ClientType.PEANUT.getCode().equals(orderOrigin) && !ClientType.GOLD_COLORED_GLASS.getCode().equals
                    (orderOrigin)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ORIGIN_MUST_BE_PEANUT_OR_GOLD_COLORED_GLASS);
            }
            String realChargesStr = dto.getRealCharges();
            if (StringUtils.isBlank(realChargesStr)) {
                return ApiResult.fail(OrderErrorCode.REAL_PRICE_IS_NOT_NULL);
            }
            String packageIdsStr = dto.getPackageIds();
            if (StringUtils.isBlank(packageIdsStr)) {
                return ApiResult.fail(OrderErrorCode.PACKAGE_IDS_IS_NOT_NULL);
            }
            String packageChargesStr = dto.getPackageCharges();
            if (StringUtils.isBlank(packageIdsStr)) {
                return ApiResult.fail(OrderErrorCode.PACKAGE_CHARGES_IS_NOT_NULL);
            }
            if (userInfo == null) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(com.hsgene.common.exception.CommonErrorCode.USER_ID_IS_NULL);
            }
            String[] realCharges = realChargesStr.split(",");
            String[] packageIds = packageIdsStr.split(",");
            String[] packageCharges = packageChargesStr.split(",");
            Double updateTotalRealCharge = 0.00;
            for (String realCharge : realCharges) {
                updateTotalRealCharge += Double.valueOf(realCharge);
            }
            GeneticTestingOrder geneticTestingOrder = orderService.findById(orderId);
            BigDecimal totalCharges = geneticTestingOrder.getTotalCharges();
            if (updateTotalRealCharge != totalCharges.doubleValue()) {
                return ApiResult.fail(OrderErrorCode.PACKAGE_PRICE_SUM_MUST_EQUAL_ORDER_PRICE);
            }
            orderService.updatePackageCharges(orderId, packageCharges, realCharges, packageIds, userId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(OrderErrorCode.UPDATE_ORDER_REAL_PRICE_IS_ERROR.getMessage(), e);
            return ApiResult.fail(OrderErrorCode.UPDATE_ORDER_REAL_PRICE_IS_ERROR);
        }
    }

    /**
     * 获取订单对应的pdf信息
     *
     * @param orderId 订单id
     * @return
     */
    @GetMapping("orders/pdf/{order_id}")
    public ApiResult<List<GeneTestPdfInfo>> getTestPdf(@PathVariable("order_id") String orderId,
                                                       HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(orderId)) {
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            List<GeneTestPdfInfo> pdfInfos = orderService.getTestPdf(orderId);
            return new ApiResult<>(200, "success", "获取报告pdf信息成功", pdfInfos);
        } catch (Exception e) {
            LOGGER.error("get order pdf infois error...", e);
            return ApiResult.fail(OrderErrorCode.ORDER_PDF_INFO_IS_ERROR);
        }
    }

    /**
     * 获取订单信息(患者展示)
     *
     * @param orderId 订单id
     * @param request
     * @return
     */
    @GetMapping("orders/patient/{order_id}")
    public ApiResult getOrderDetails(@PathVariable("order_id") String orderId, HttpServletRequest request) {
        try {
            LOGGER.info("query order details info ...");
            if (StringUtils.isEmpty(orderId)) {
                LOGGER.error("order id is not null...");
                return ApiResult.fail(OrderErrorCode.ORDER_ID_IS_NOT_NULL);
            }
            //校验token
            IJWTInfo jwtInfo = checkToken(request);
            if (jwtInfo == null) {
                LOGGER.error("token is not null...");
                return ApiResult.fail(CommonErrorCode.AUTHORIZATION_PARSE_EXCEPTION);
            }
            GeneticTestPatientShowInfo showInfo = orderService.getOrderDetailsByOrderId(orderId);
            if (showInfo == null) {
                return ApiResult.fail(OrderErrorCode.ORDER_NOT_EXISTED);
            }
            return new ApiResult<>(200, "success", "获取详情信息成功", showInfo);
        } catch (Exception e) {
            LOGGER.error("get order details info is error...", e);
            return ApiResult.fail(OrderErrorCode.QUERY_ORDER_DETAILS_IS_ERROR);
        }
    }

    /**
     * @param sortField 排序字段
     * @param sortType  排序类型
     * @param condition 查询条件
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 检查排序字段
     * @author maodi
     * @createDate 2019/1/22 9:43
     */
    public static ErrorCode checkSortField(String sortField, String sortType, QueryTestingProductOrderCondition
            condition) {
        if (StringUtils.isBlank(sortField)) {
            condition.setSortField("createDateTime");
        } else {
            if ("create_date_time".equals(sortField)) {
                condition.setSortField("createDateTime");
            } else if ("update_date_time".equals(sortField)) {
                condition.setSortField("updateDateTime");
            } else if ("total_charges".equals(sortField)) {
                condition.setSortField("totalCharges");
            } else if ("total_commission".equals(sortField)) {
                condition.setSortField("totalCommission");
            } else {
                if ("createDateTime".equals(sortField) || "updateDateTime".equals(sortField) || "totalCharges".equals
                        (sortField) || "totalCommission".equals(sortField)) {
                    condition.setSortField(sortField);
                } else {
                    return OrderErrorCode.SORT_FIELD_IS_ERROR;
                }
            }
        }
        if (StringUtils.isBlank(sortType)) {
            condition.setSortType("desc");
        } else {
            if (!"desc".equalsIgnoreCase(sortType) && !"asc".equalsIgnoreCase(sortType)) {
                return com.hsgene.common.exception.CommonErrorCode.SORT_ORDER_IS_ERROR;
            }
            condition.setSortType(sortType);
        }
        return null;
    }

    /**
     * @description 根据当前时间和订单下单时间返回倒计时
     * @author maodi
     * @createDate 2019/2/20 14:20
     * @param orderId 订单id
     * @return com.hsgene.common.util.result.ApiResult<java.lang.String>
     */
    @GetMapping("orders/pay/countdown/{order_id}")
    public ApiResult<Long> countDown(@PathVariable("order_id") String orderId) {
        long currentTime = System.currentTimeMillis();
        GeneticTestingOrder geneticOrder = orderService.findById(orderId);
        long createDateTime = geneticOrder.getCreateDateTime().getTime();
        long countDown = (3600000 + createDateTime) - currentTime;
        if (countDown < 0) {
            countDown = 0;
        }
        return ApiResult.succ(countDown);
    }

}
